package org.example.game.weekly.game441;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author wyatt
 * @Data 2024/08/03 20:46
 */
public class Solution002 {

    public static void main(String[] args) {
        List<Integer> res = new Solution002().solveQueries(new int[]{14,14,4,2,19,19,14,19,14}, new int[]{8});

        for (int i = 0; i < res.size(); i++) {
            System.out.println(res.get(i));
        }
    }

    public List<Integer> solveQueries(int[] nums, int[] queries) {

        List<Integer> res = new ArrayList<>();
        Map<Integer, Integer> all = new HashMap<>();
        Map<Integer, List<Integer>> numIndexMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            numIndexMap.putIfAbsent(nums[i], new ArrayList<>());
            numIndexMap.get(nums[i]).add(i);
        }

        for (Integer value : numIndexMap.keySet()) {
            List<Integer> indexList = numIndexMap.get(value);
            if(indexList.size() == 1){
                all.put(indexList.get(0), -1);
            }else {
                for (int i = 0; i < indexList.size(); i++) {
                    all.put(indexList.get(i), calMinDistance(i, indexList, nums.length));
                }
            }
        }

        for (int i = 0; i < queries.length; i++) {
            res.add(all.getOrDefault(queries[i], -1));
        }

        return res;
    }

    private Integer calMinDistance(int index, List<Integer> indexList, int length) {
        int pre = index -1 < 0 ? indexList.get(indexList.size() - 1) : indexList.get(index - 1);
        int next = index + 1 >= indexList.size() ? indexList.get(0) : indexList.get(index + 1);
        int preIndex = Math.min( Math.abs(indexList.get(index) - pre), length - Math.max(indexList.get(index), pre) + Math.min(indexList.get(index), pre));
        int nextIndex = Math.min( Math.abs(next - indexList.get(index)), length - Math.max(next, indexList.get(index)) + Math.min(next, indexList.get(index)));
        return Math.min( preIndex, nextIndex);
    }

}
